//
//  FileManager.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/22.
//

import Foundation
import UIKit
import Photos
class PKFileManager : NSObject {
    static let shared = PKFileManager()
    func generateImageFileName(ext: String = "png") -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMdd_HHmmss_SSS"
        let dateString = formatter.string(from: Date())
        return "IMG_\(dateString).\(ext)"
    }
    
    
    func showPermissionAlert() {
        guard let topVC = UIApplication.shared.windows.first(where: \.isKeyWindow)?.rootViewController else { return }

        let alert = UIAlertController(title: "Unable to access the photo album", message: "Please enable access to photos in the \("Settings") to save the pictures.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Go to Settings", style: .default, handler: { [self] _ in
            openAppSettings()
        }))
        topVC.present(alert, animated: true, completion: nil)
    }
    
    func openAppSettings() {
        if let appSettings = URL(string: UIApplication.openSettingsURLString),
           UIApplication.shared.canOpenURL(appSettings) {
            UIApplication.shared.open(appSettings, options: [:], completionHandler: nil)
        }
    }
    func saveImageToPhotoLibrary(_ image: UIImage) {
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async { [self] in
                switch status {
                case .authorized, .limited:
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }) { success, error in
                        print(success ? "保存成功" : "保存失败: \(error?.localizedDescription ?? "")")
                    }
                case .denied, .restricted:
                    showPermissionAlert()
                default:
                    break
                }
            }
        }
    }

    
    func saveImageToDocuments(image: UIImage) -> URL? {
        guard let data = image.jpegData(compressionQuality: 0.8) else { return nil }
        
        let fileName = generateImageFileName()
        let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documents.appendingPathComponent(fileName)

        do {
            try data.write(to: fileURL)
            print("图片已保存到: \(fileURL)")
            return fileURL
        } catch {
            print("保存失败: \(error)")
            return nil
        }
    }
    
    // 保存图片到磁盘
    func saveImageToDisk(_ image: UIImage, fileName: String) -> String? {
        if let data = image.jpegData(compressionQuality: 0.9) {
            let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let fileURL = url.appendingPathComponent("\(fileName).jpg")
            try? data.write(to: fileURL)
            return fileURL.path
        }
        return nil
    }
    func generateTimestampFileName(prefix: String = "IMG") -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMdd_HHmmss" // 例如：20250528_143512
        let timestamp = formatter.string(from: Date())
        return "\(prefix)_\(timestamp)"
    }
    
    func loadImageFromDocuments(fileName: String) -> UIImage? {
        let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documents.appendingPathComponent(fileName)
        return UIImage(contentsOfFile: fileURL.path)
    }
    func loadAllImagesFromDocuments() -> [UIImage] {
        var images: [UIImage] = []
        let fileManager = FileManager.default

        // 获取 Documents 目录路径
        guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return []
        }

        do {
            // 列出所有文件
            let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)

            // 筛选出图片文件
            for url in fileURLs {
                let ext = url.pathExtension.lowercased()
                if ["png", "jpg", "jpeg"].contains(ext) {
                    if let image = UIImage(contentsOfFile: url.path) {
                        images.append(image)
                    }
                }
            }
        } catch {
            print("读取目录失败: \(error)")
        }

        return images
    }
    func loadAllImageFilesFromDocumentsWithAllDetails() -> [(image: UIImage, fileName: String, url: URL)] {
        var results: [(UIImage, String, URL)] = []

        guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return []
        }

        do {
            let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)

            for url in fileURLs {
                let ext = url.pathExtension.lowercased()
                if ["png", "jpg", "jpeg"].contains(ext),
                   let image = UIImage(contentsOfFile: url.path) {
                    results.append((image, url.lastPathComponent, url))
                }
            }
        } catch {
            print("读取失败: \(error)")
        }

        return results
    }
    
}

